<template>
  <el-row id="app" class="max-box" v-cloak>
    <!--<el-scrollbar ref="myAppScrollbar" style="height:100%;">-->
    <el-tabs
      style="height: 100%"
      class="app-tab"
      v-model="activeName"
      type="card"
      @tab-click="handleClick"
      ref="tabs"
    >
      <!-- 动态增加 -->
      <el-tab-pane
        style="height: 100%"
        v-for="(element, idx) in homeMenu"
        :label="element.label"
        :name="element.name"
        v-if="element.show"
      >
        <el-scrollbar style="height: calc(100% - 0px)">
          <el-row class="nav-btn">
            <el-col
              v-for="nav in element.children"
              v-show="!nav.isHideFlag"
              :span="3"
              class="second-menu"
            >
              <router-link
                :to="nav.path"
                :name="nav.path"
                replace
                :class="{ active: $route.meta.active === nav.path }"
                :title="$t(nav.label)"
              >
                {{ $t(nav.label) }}
              </router-link>
            </el-col>
          </el-row>

          <el-row v-if="element.main.type === 'router-view'" class="main-cnt">
            <el-main>
              <keep-alive>
                <router-view
                  :name="element.main.id || 'default'"
                  v-if="$route.meta.keepAlive"
                />
              </keep-alive>
              <router-view
                :name="element.main.id || 'default'"
                v-if="!$route.meta.keepAlive"
              />
            </el-main>
          </el-row>
          <el-row
            v-else-if="element.main.type === 'iframe'"
            class="main-cnt-iframe"
          >
            <iframe
              scrolling="auto"
              :src="element.main.src()"
              :id="element.main.id"
              width="100%"
              height="100%"
              style="border: none"
            ></iframe>
          </el-row>
          <el-row
            v-else-if="element.main.type === 'component'"
            class="main-cnt-iframe"
          >
            <custom-list v-if="element.name === 'four'"></custom-list>
            <re-commend
              @routeToNine="routeToNine"
              v-else-if="element.name === 'ten'"
            ></re-commend>
          </el-row>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>

<script>
import commonApi from "@/api/common";
import ReCommend from "@/views/recommend/recommend";
import { saveTransCusInfo } from "@/api/bankBiz/loss/loss";
import $ from "jquery";
import { getAccessToken, getUserToken } from "@/api/app";

export default {
  name: "app",
  data() {
    return {
      homeMenu: window.ctpMenuOption.home.tabs,
      activeName: window.ctpMenuOption.home.activeName(),
      // tabs 首次点击标识
      tabsLastActiveLink: {},
      kebRootFlag: false,
      /******************************** 综合业务二级菜单 ************************************/
      personal: "/personal",
      company: "/company",
      publicInfo: "/publicInfo",
      kbp: "/kbp",
      reportLoss: "/reportLoss",

      /******************************** 调单管理二级菜单 ************************************/
      adjustment: "/adjustment",
      /******************************** 面签客户信息二级菜单 ************************************/
      faceuserinfo: "/faceuserinfo",
      //工单历史
      workorder: "/workorder",
      //录音历史
      soundrecording: "/soundrecording",
      /******************************** 历史贷款审批记录二级菜单 ************************************/
      loanhistory: "/loanhistory",
      /******************************** 答题模板 ************************************/
      ansyertemp: "/ansyertemp",

      /******************************** 视频业务二级菜单 ************************************/
      cardActive: "/cardActive",
      realEstateRecovery: "/realEstateRecovery",
      accRestrictLift: "/accRestrictLift",
      forOpenHouse: "/forOpenHouse",
      phoneBankCardActive: "/phoneBankCardActive",
      phoneBankForOpenHouse: "/phoneBankForOpenHouse",
      phoneBankFinancialRisk: "/phoneBankFinancialRisk",
      /******************************** 一级权限菜单 ************************************/
      integratedFlag: false,
      creditCardFlag: false,
      videoFlag: false,
      etsFlag: false,
      intelligentFlag: false,
      webCollaboFlag: false,
      faceRecogFlag: true,
      kbpFlag: true,
    };
  },
  components: {
    ReCommend,
  },
  created() {
    // 权限
    let langName = location.search;
    if (langName) {
      let lang = this.getUrl("lang");
      let agentId = this.getUrl("agentId");
      let userId = this.getUrl("userId");
      let role = this.getUrl("role");
      // 中英文切换
      this.changeLanguage(lang);
      // 电子工单传值
      this.$store.commit("SET_LANG", lang);
      this.$store.commit("SET_USERID", userId);
      this.$store.commit("SET_ROLE", role);
      this.$store.commit("SET_AGENTID", agentId);
    }
    if (window.Settings.offlineSwitch) {
      this.$store.commit("SET_OFFLINESTATUS", false);
    }
    if (!window.Settings.authSwitch) {
      console.log("权限false");
      let resources = window.Settings.authParam;
      this.$store.commit("SET_PERMISSION", resources);
      this.authInit(resources);
    }
    if (!window.Settings.themeSwitch) {
      window.document.documentElement.setAttribute(
        "data-theme",
        window.Settings.theme
      );
    }
  },
  mounted: function () {
    getUserToken();

    /************************************* 接收事件初始化 *****************************************/
    let self = this;
    // 卡激活-小程序
    window.eventEmitter.$on("EventVideoTabActive", () => {
      console.log("receive video tab active");
      self.activeName = "third";
      self.$router.push({ name: "cardActive" });
      self.isShowCardRingFlag("third", "/phoneBankCardActive", "/cardActive");
    });
    // 卡激活-手机银行
    window.eventEmitter.$on("EventPhoneBankCardRingTabActive", () => {
      console.log("receive video tab active");
      self.activeName = "third";
      self.$router.push({ name: "phoneBankCardActive" });
      self.isShowCardRingFlag("third", "/cardActive", "/phoneBankCardActive");
    });
    // 对公开户-小程序
    window.eventEmitter.$on("EventOpenHouseVideoTabActive", () => {
      console.log("receive open house video tab active");
      self.activeName = "third";
      self.$router.push({ name: "forOpenHouse" });
      self.isShowCardRingFlag(
        "third",
        "/phoneBankForOpenHouse",
        "/forOpenHouse"
      );
    });
    // 对公开户-手机银行
    window.eventEmitter.$on("EventPhoneBankOpenRingTabActive", () => {
      console.log("receive open house video tab active");
      self.activeName = "third";
      self.$router.push({ name: "phoneBankForOpenHouse" });
      self.isShowCardRingFlag(
        "third",
        "/forOpenHouse",
        "/phoneBankForOpenHouse"
      );
    });
    // 理财风险评估-手机银行
    window.eventEmitter.$on("EventPhoneBankFRARingTabActive", () => {
      console.log("receive video tab active");
      self.activeName = "third";
      self.$router.push({ name: "phoneBankRiskAssessment" });
    });
    // 挂机
    window.eventEmitter.$on("EventCallReleased", () => {
      self.$store.commit("SET_OFFLINESTATUS", true);
    });
    // 话后处理
    window.eventEmitter.$on("EventAfterCall", () => {
      if (self.$store.getters.GET_OFFLINESTATUS) {
        self.$store.commit("SET_PERSONALFLAG", false);
        self.$store.commit("SET_COMPANYFLAG", false);
        self.$store.commit("SET_LOSSFLAG", false);
        sessionStorage.removeItem("accName");
        sessionStorage.removeItem("bankNo");
        sessionStorage.removeItem("openBankName");
        sessionStorage.removeItem("bankNoList");
        sessionStorage.removeItem("customerNo");
        sessionStorage.removeItem("customerIdType");
        sessionStorage.removeItem("customerIdNo");
        sessionStorage.removeItem("customerPhone");
        Constants.Model = {};
      }
    });
    // 获取坐席信息
    window.eventEmitter.$on("EventAgentInfo", (data) => {
      if (!window.Settings.authSwitch) {
        return;
      }
      let resources = data.resources;
      self.$store.commit("SET_PERMISSION", resources);
      self.authInit(resources);
      // console.log("从工作台获取的座席信息==", resources);
      // let agentrole = sele.$store.GET_AGENTINFO.agentInfo.resources.split(",");
      // console.log("工作台拿的角色详情", agentrole);
      if (window.Settings.themeSwitch) {
        CommonParameters.getRetCodeValueByNo(
          "THEME",
          CommonParameters.codeShowHandler,
          data.tenantId
        );
      }
    });
    // 进线验密获取验密标识
    window.eventEmitter.$on("EventCallRecordChange", (data) => {
      if (data.userData) {
        if (
          "01" == data.userData.i_verifyflag &&
          ("02" == data.userData.p_verifytype ||
            "06" == data.userData.p_verifytype)
        ) {
          self.$store.commit("SET_PERSONALFLAG", true);
          self.$store.commit("SET_LOSSFLAG", true);
        } else if (
          "01" == data.userData.i_verifyflag &&
          "01" == data.userData.p_verifytype
        ) {
          self.$store.commit("SET_COMPANYFLAG", true);
        }
      }
      saveTransCusInfo();
    });
    // 三方验密获取验密标识
    window.eventEmitter.$on("EventVerifyResult", (data) => {
      if (data) {
        if (
          "01" == data.i_verifyflag &&
          ("02" == data.p_verifytype || "06" == data.p_verifytype)
        ) {
          self.$store.commit("SET_PERSONALFLAG", true);
          self.$store.commit("SET_LOSSFLAG", true);
        } else if ("01" == data.i_verifyflag && "01" == data.p_verifytype) {
          self.$store.commit("SET_COMPANYFLAG", true);
        }
      }
    });
    // 自动跳转工单页面
    window.eventEmitter.$on("createWorkOrderFromSummary", () => {
      this.activeName = "five";
    });
  },
  methods: {
    // 权限解析
    checkAuth(resources, code) {
      //返回满足条件的第一个值
      resources = resources.split(",").find((item) => item == code);
      return resources ? true : false;
    },
    // 二级菜单权限解析
    secondMenuCheck(resources, code, name, path) {
      if (!this.checkAuth(resources, code)) {
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == name
        ).children = window.ctpMenuOption.home.tabs
          .find((item) => item.name == name)
          .children.filter((item) => item.path != path);
      }
    },
    // 权限初始化
    authInit(resources) {
      resources = resources.trim();
      //面签模块权限
      window.ctpMenuOption.home.tabs.find(
        (item) => item.name == "adjustment"
      ).show = this.checkAuth(resources, "adjustment");
      window.ctpMenuOption.home.tabs.find(
        (item) => item.name == "faceuserinfo"
      ).show = this.checkAuth(resources, "faceuserinfo");
      window.ctpMenuOption.home.tabs.find(
        (item) => item.name == "loanhistory"
      ).show = this.checkAuth(resources, "loanhistory");

      window.ctpMenuOption.home.tabs.find(
        (item) => item.name == "workorder"
      ).show = this.checkAuth(resources, "workorder");

      window.ctpMenuOption.home.tabs.find(
        (item) => item.name == "soundrecording"
      ).show = this.checkAuth(resources, "soundrecording");

      //IntegratedServices
      window.ctpMenuOption.home.tabs.find((item) => item.name == "first").show =
        this.checkAuth(resources, "first");
      window.ctpMenuOption.home.tabs.find((item) => item.name == "third").show =
        this.checkAuth(resources, "VideoBusi");
      if ("iframe" == window.Settings.ewsModule) {
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "five"
        ).show = this.checkAuth(resources, "EWS_order");
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "four"
        ).show = false;
      } else {
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "four"
        ).show = this.checkAuth(resources, "EWS_order");
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "five"
        ).show = false;
      }
      if ("iframe" == window.Settings.kbpModule) {
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "nine"
        ).show = this.checkAuth(resources, "KnowledgeQuery");
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "eleven"
        ).show = false;
      } else {
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "eleven"
        ).show = this.checkAuth(resources, "KnowledgeQuery");
        window.ctpMenuOption.home.tabs.find(
          (item) => item.name == "nine"
        ).show = false;
      }
      window.ctpMenuOption.home.tabs.find((item) => item.name == "ten").show =
        this.checkAuth(resources, "IntelligentRecommend");
      this.secondMenuCheck(resources, "PersonalBusi", "first", "/personal");
      this.secondMenuCheck(resources, "CompanyBusi", "first", "/company");
      this.secondMenuCheck(resources, "FinancialNews", "first", "/publicInfo");
      this.secondMenuCheck(resources, "ReportLoss", "first", "/reportLoss");

      // 视频业务-小程序
      this.secondMenuCheck(resources, "CardActiv", "third", "/cardActive");
      this.secondMenuCheck(
        resources,
        "Unfreeze",
        "third",
        "/realEstateRecovery"
      );
      this.secondMenuCheck(
        resources,
        "LimitedRelease",
        "third",
        "/accRestrictLift"
      );
      this.secondMenuCheck(
        resources,
        "PublicAccounts",
        "third",
        "/forOpenHouse"
      );
      // 视频业务-手机银行
      this.secondMenuCheck(
        resources,
        "phoneBankCardActive",
        "third",
        "/phoneBankCardActive"
      );
      this.secondMenuCheck(
        resources,
        "phoneBankForOpenHouse",
        "third",
        "/phoneBankForOpenHouse"
      );
      this.secondMenuCheck(
        resources,
        "phoneBankRiskAssessment",
        "third",
        "/phoneBankRiskAssessment"
      );
      // 默认激活一级菜单
      if (this.checkAuth(resources, "IntelligentRecommend")) {
        this.activeName = "ten";
      } else if (this.checkAuth(resources, "IntegratedServices")) {
        this.activeName = "first";
        window.ctpMenuOption.home.redirectName = "personal";
        this.$router.push({ name: window.ctpMenuOption.home.redirectName });
      } else if (this.checkAuth(resources, "VideoBusi")) {
        this.activeName = "third";
        window.ctpMenuOption.home.redirectName = "cardActive";
        if (window.Settings.videoAuthRedirect == "phoneBank") {
          window.ctpMenuOption.home.redirectName = "phoneBankCardActive";
        }
        this.$router.push({ name: window.ctpMenuOption.home.redirectName });
      } else if (this.checkAuth(resources, "EWS_order")) {
        if ("iframe" == window.Settings.ewsModule) {
          this.activeName = "five";
        } else {
          this.activeName = "four";
        }
      } else if (this.checkAuth(resources, "KnowledgeQuery")) {
        if ("iframe" == window.Settings.kbpModule) {
          this.activeName = "nine";
        } else {
          this.activeName = "eleven";
        }
      }
    },
    // 显示隐藏页签
    isShowCardRingFlag(name, fromShowPath, toShowPath) {
      let menu = window.ctpMenuOption.home.tabs.find(
        (menu) => menu.name == name
      );
      menu.children.forEach((item) => {
        if (item.path == fromShowPath) {
          item.isHideFlag = true;
        } else if (item.path == toShowPath) {
          item.isHideFlag = false;
        }
      });
    },
    // 获取请求路径参数
    getUrl(name) {
      var reg = new RegExp("(|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
      if (reg.test(location.href)) {
        return unescape(RegExp.$2.replace(/\+/g, " "));
      } else {
        return "";
      }
    },
    // 国际化切换
    changeLanguage(lang) {
      if (lang === "en_US") {
        this.$i18n.locale = "en_US";
      } else {
        this.$i18n.locale = "zh_CN";
      }
    },
    // 获取权限
    getRootFn() {
      let params = {
        "UserDTO.roleNos": this.$store.getters.GET_ROLE,
        "UserDTO.userNo": this.$store.getters.GET_USERID,
      };
      commonApi.getRoot(params).then((response) => {
        if (response.code === "ok") {
          if (!response.retObj.length) {
            this.$store.commit("SET_PERSONAL", false);
            return;
          }
          for (let i = 0; i < response.retObj.length; i++) {
            switch (response.retObj[i].funcNo) {
              case "personal":
                this.$store.commit("SET_PERSONAL", true);
                Utils.log.info(this.$store.getters.GET_PERSONAL);
                this.$router.replace({ name: "personal" });
                break;
              case "company":
                this.$store.commit("SET_COMPANY", true);
                if (this.$store.getters.GET_PERSONAL) {
                  this.$router.replace({ name: "personal" });
                } else {
                  this.$router.replace({ name: "company" });
                }
                break;
              case "publicInfo":
                this.$store.commit("SET_PUBLICINFO", true);
                if (this.$store.getters.GET_PERSONAL) {
                  this.$router.replace({ name: "personal" });
                } else if (this.$store.getters.GET_COMPANY) {
                  this.$router.replace({ name: "company" });
                } else {
                  this.$router.replace({ name: "publicInfo" });
                }
                break;
              case "kbpOVS":
                this.$store.commit("SET_KBP", true);
                this.kebRootFlag = true;
                if (this.$store.getters.GET_PERSONAL) {
                  this.$router.replace({ name: "personal" });
                } else if (this.$store.getters.GET_COMPANY) {
                  this.$router.replace({ name: "company" });
                } else if (this.$store.getters.GET_PUBLICINFO) {
                  this.$router.replace({ name: "publicInfo" });
                } else {
                  this.$router.replace({ name: "kbp" });
                }
                break;
              case "reportLoss":
                this.$store.commit("SET_REPORTLOSS", true);
                if (this.$store.getters.GET_PERSONAL) {
                  this.$router.replace({ name: "personal" });
                } else if (this.$store.getters.GET_COMPANY) {
                  this.$router.replace({ name: "company" });
                } else if (this.$store.getters.GET_PUBLICINFO) {
                  this.$router.replace({ name: "publicInfo" });
                } else if (this.$store.getters.GET_KBP) {
                  this.$router.replace({ name: "kbp" });
                } else {
                  this.$router.replace({ name: "reportLoss" });
                }
                break;
              case "ewo":
                this.$store.commit("SET_EWO", true);
                if (this.$store.getters.GET_PERSONAL) {
                  this.$router.replace({ name: "personal" });
                } else if (this.$store.getters.GET_COMPANY) {
                  this.$router.replace({ name: "company" });
                } else if (this.$store.getters.GET_PUBLICINFO) {
                  this.$router.replace({ name: "publicInfo" });
                } else if (this.$store.getters.GET_KBP) {
                  this.$router.replace({ name: "kbp" });
                } else if (this.$store.getters.GET_REPORTLOSS) {
                  this.$router.replace({ name: "reportLoss" });
                } else {
                  this.$router.replace({ name: "ewo" });
                }
                break;
              case "accSearch":
                this.$store.commit("SET_ACCSEARCH", true);
                break;
              case "cheque":
                this.$store.commit("SET_CHEQUE", true);
                break;
              case "loanBusiness":
                this.$store.commit("SET_LOANBUSINESS", true);
                break;
              case "messageService":
                this.$store.commit("SET_MESSAGESERVICE", true);
                break;
              case "accInfo":
                this.$store.commit("SET_ACCINFO", true);
                break;
              case "companyCheque":
                this.$store.commit("SET_COMPANYCHEQUE", true);
                break;
              case "foreignCurrencyRate":
                this.$store.commit("SET_FOREIGNCURRENCYRATE", true);
                break;
              case "foreignExchangeRate":
                this.$store.commit("SET_FOREIGNEXCHANGERATE", true);
                break;
              case "organizationName":
                this.$store.commit("SET_ORGANIZATIONNAME", true);
                break;
              case "oldAndNewLine":
                this.$store.commit("SET_OLDANDNEWLINE", true);
                break;
              case "nonContractualLoss":
                this.$store.commit("SET_NONCONTRACTUALLOSS", true);
                break;
              case "cardLossOtherServices":
                this.$store.commit("SET_CARDLOSSOTHERSERVICES", true);
                break;
              case "lossRecord":
                this.$store.commit("SET_LOSSRECORD", true);
                Utils.log.info("123");
                Utils.log.info(this.$store.getters.GET_LOSSRECORD);
                break;
              case "cardServiceRecord":
                this.$store.commit("SET_CARDSERVICERECORD", true);
                break;
              case "faq":
                this.$store.commit("SET_FAQ", true);
                break;
              case "search":
                this.$store.commit("SET_SEARCH", true);
                break;
            }
          }
        } else {
          Utils.log.info(response);
        }
      });
    },
    // 一级菜单切换
    handleClick(tab) {
      console.log(
        "current tab name is: " +
          tab.name +
          ",+++ " +
          JSON.stringify(this.tabsLastActiveLink[tab.name])
      );
      // 激活首页
      for (let i = 0; i < this.homeMenu.length; i++) {
        let element = this.homeMenu[i];
        if (element.name === tab.name) {
          // 首次点击，设置标识
          if (!this.tabsLastActiveLink[tab.name]) {
            let activeValue = element.main.defaultActive;
            if (
              window.Settings.videoAuthRedirect == "phoneBank" &&
              tab.name == "third"
            ) {
              activeValue = element.main.defaultPhoneBankActive;
            }
            this.tabsLastActiveLink[tab.name] = {
              activeName: activeValue,
            };
          }
          this.$router.push({
            path: this.tabsLastActiveLink[tab.name].activeName,
            meta: { keepAlive: true, ifDoFresh: false, isBack: false },
          });
          break;
        }
      }
    },
    // 跳转首页
    routeToNine() {
      this.activeName = "first";
    },
  },
  updated: function () {
    // 一级Tab路由页面保持
    let tmpActive = "";
    if (this.$route.meta.isBack && this.$route.meta.flag) {
      tmpActive = this.$route.meta.active + "/" + this.$route.meta.flag;
    } else {
      tmpActive = this.$route.meta.active;
    }

    // 默认激活的tab首页
    this.tabsLastActiveLink[this.activeName] = {
      activeName: tmpActive,
    };

    // 二级Route Link路由页面保持
    // 默认激活的tab首页
    let query = 'a[name="' + this.$route.meta.active + '"]';
    if (document.querySelector(query)) {
      document.querySelector(query).href = "#" + tmpActive;
    }
  },
};
</script>

<style scoped>
[v-cloak] {
  display: none;
}

.max-box {
  height: 100%;
  width: 100%;
}

.nav-btn {
  padding: 0 5px;
}

.second-menu {
  height: 32px;
  line-height: 32px;
  text-align: center;
  min-width: 100px;
  border: 1px #ececec solid;
  background-color: #f5f7fa;
}

.second-menu:first-child {
  border-bottom-left-radius: 15px;
}

.second-menu:last-child {
  border-top-right-radius: 15px;
}

.nav-btn a {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-decoration: none;
  font-size: 14px;
}

.main-cnt {
  height: calc(100% - 45px);
  overflow-y: hidden;
}

.main-cnt-iframe {
  height: calc(100% - 5px);
  overflow-y: hidden;
}

.active {
  /*color: #B50029;*/
  color: #3167af;
  /*border-bottom: 1px #B50029 solid;*/
}
</style>
